package tencent

import (
	"context"

	"gitee.com/go-course/go12/devcloud-mini/cmdb/apps/resource"
	"gitee.com/go-course/go12/devcloud-mini/cmdb/provider"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/infraboard/mcube/ioc/config/logger"
	"github.com/rs/zerolog"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
)

func NewCvmProvider(c *Client) *CvmProvider {
	// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
	// 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
	// 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
	credential := common.NewCredential(
		c.secretId,
		c.secretKey,
	)
	// 实例化一个client选项，可选的，没有特殊需求可以跳过
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "cvm.tencentcloudapi.com"
	// 实例化要请求产品的client对象,clientProfile是可选的
	client, err := cvm.NewClient(credential, c.region, cpf)
	if err != nil {
		panic(err)
	}

	return &CvmProvider{
		client: client,
		log:    logger.Sub("cvm"),
	}
}

type CvmProvider struct {
	client *cvm.Client
	log    *zerolog.Logger
}

func (c *CvmProvider) Sync(
	ctx context.Context,
	req *provider.SyncRequest,
	hook provider.ResourceHandler) error {
	// 实例化一个请求对象,每个接口都会对应一个request对象
	request := cvm.NewDescribeInstancesRequest()

	// 返回的resp是一个DescribeInstancesResponse的实例，与请求对象对应
	response, err := c.client.DescribeInstances(request)
	if err != nil {
		return err
	}

	if len(response.Response.InstanceSet) == 0 {
		hook(nil)
	}

	// CVM ==> Resource
	for i := range response.Response.InstanceSet {
		ins := response.Response.InstanceSet[i]
		c.log.Debug().Msgf("sync cvm %s", *ins.InstanceId)
		// 资源转换
		res := resource.NewResource()
		res.Spec.Zone = tea.StringValue(ins.Placement.Zone)
		res.Meta.Id = tea.StringValue(ins.InstanceId)
		res.Spec.Type = tea.StringValue(ins.InstanceType)
		res.Spec.Cpu = int32(*ins.CPU)
		res.Spec.Memory = int32(*ins.Memory)
		res.Spec.Name = tea.StringValue(ins.InstanceName)
		res.Spec.Extra["os_name"] = tea.StringValue(ins.OsName)
		res.Status.Phase = tea.StringValue(ins.InstanceState)
		// 将转换完成的资源交给下游
		hook(res)
	}

	return nil
}
